//
//  MainMenu.m
//  Pocket Doctor alpha version
//
//  Created by Sherif, Yin, Taylor, Jacob, Anna, Mike on 11-10-25.
//  Copyright (c) 2011 __Sytjam__. All rights reserved.
//
//Class Description: - Main Menu; this is where everything happens.
//                     all views are accessible from here (except first time launch)
//                     emergency contact is loaded and ready to use (if set up)
//                     next reminder is loaded and displayed at the bottom.
//                   - Easiest way to check medications and times is through Calendar.
//                   - Editing must be done from medicine view
//
//Known Bugs: 
//  - Nearby Pharmacy may ask more than once for location verification (even if you say no).
//  - When receiving a notification and the application is open and you are on main menu view              the next reminder is not refreshed with it.
//            - Reminders displayed are only those saved in the local notification (so, if you have a reminder due tomorrow; after the notification goes off; the next reminder will display "no upcoming reminders" BUT; in reality... the reminder will fire next week as well.
//

#import "MainMenu.h"
#import "Passcode.h"
#import "Preferences.h"
#import "LogKeeper.h"
#import "MedSearch.h"
#import "Information.h"
#import "AppDelegate.h"
#import "NearbyPharmacy.h"

int request = 1;
int move = 0;

int clockSettings = 0;
int daySettings = 0;

UIControl *c;

@implementation MainMenu

@synthesize tryURL, meds, cal, pharm, history, Search, settings, emergency, info, nextReminder, nextReminderLabel, emergencyInstructions, emergencyNumber, emergencyArrows, webView, testingConnection, activityIndicator, URLActionImage;
@synthesize pc, log, ms, sets, about, aD, np;

/*Go to Medicine view*/
- (IBAction)GoToMedicine:(id)sender{
    if (pc == nil){
        Passcode *pcObject = [[Passcode alloc]initWithNibName:@"Passcode" bundle:nil];
        self.pc = pcObject;
        [pcObject release];
    }
    
    pc.medicineOrCalendar = 0;
    
    pc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:pc animated:YES];
    
    pc = nil;
}

/*Go to Calendar view (not complete)*/
- (IBAction)GoToCalendar:(id)sender{
    
    if (pc == nil){
        Passcode *pcObject = [[Passcode alloc]initWithNibName:@"Passcode" bundle:nil];
        self.pc = pcObject;
        [pcObject release];
    }
    
    pc.medicineOrCalendar = 1;
    
    pc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:pc animated:YES];
    
    pc = nil;
    
    /* *Object = [[ alloc]initWithNibName:@"" bundle:nil];
     self. = ;
     [Object release];*/
    //[nav GoToCalendar];
}

- (IBAction)GoToLogs:(id)sender{
    if (log == nil){
        LogKeeper *logObject = [[LogKeeper alloc]initWithNibName:@"LogKeeper" bundle:nil];
        self.log = logObject;
        [logObject release];
    }
    
    log.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:log animated:YES];
    
    log = nil; //can be removed for the application to remember where u left the list.
}

- (IBAction)GoToSearch:(id)sender{
    if (ms == nil){
        MedSearch *msObject = [[MedSearch alloc]initWithNibName:@"MedSearch" bundle:nil];
        self.ms = msObject;
        [msObject release];
    }
    
    ms.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:ms animated:YES];
}

//Check for connection by loading google in the background
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    testingConnection.hidden = false;
    activityIndicator.hidden = false;
    testingConnection.text = @"Establishing Connection";
    [activityIndicator startAnimating];
        
}

//if connection exists; asking for confirmation of location
- (void)displayLabel{
    
    testingConnection.hidden = true;
    activityIndicator.hidden = true;
    [activityIndicator stopAnimating];
    URLActionImage.hidden = true;
    
    [self enableButtons:YES];
    
    [self EmergencyButtonLetGo:emergency];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
    
    emergencyInstructions.alpha = 0;
    
    [UIView commitAnimations];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Use Location" message:@"Permission to use location." delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
    
    [alert show];
    [alert release];
    
    request = 0;

}

//Found connection (wait 1.5 seconds for location permission) this time delay is for
//background rendering; since the alert will be sluggish (for speed); it is safer
//to wait 1.5 seconds than slow things down.
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    testingConnection.text = @"Connection Established";
    
    if (tryURL == 0) {
        
        //Alert will be laggy if this function is there.
        [self performSelector:@selector(displayLabel) withObject:nil afterDelay:1.5];
                
        tryURL = 1;
    }
}

//Failed to find an internet connection
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    testingConnection.hidden = true;
    activityIndicator.hidden = true;
    testingConnection.text = @"Connection Error";
    [activityIndicator stopAnimating];
    URLActionImage.hidden = true;
    
    [self enableButtons:YES];
    
    [self EmergencyButtonLetGo:emergency];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection Error" message:@"Would you like to continue anyways." delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
    
    [alert show];
    [alert release];
}

/*Access google places on browser and locates the nearest pharmacies
 This was our choice over google maps; because you are given the name and location on map of
 the place*/
- (IBAction)GoToPharmacy:(id)sender{
    tryURL = 0;
    if (tryURL == 0){
        [self enableButtons:NO];
        URLActionImage.hidden = false;
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];
    }
    
}



/*Handles the difference between a normal alert and the pharmacy alert to access location
 Handles all alerts*/
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // the user clicked one of the OK buttons
    if (buttonIndex == 1)
    {
        if (request == 2) {
            if (sets == nil) {
                Preferences *setsObject = [[Preferences alloc]initWithNibName:@"Preferences" bundle:nil];
                self.sets = setsObject;
                [setsObject release];
            }
            
            sets.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentModalViewController:sets animated:YES];
            
            [sets ChooseEmergencyContacts];
            
            sets = nil;
            
        }
        /*[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.ca/m/places?hl=en#ipd:mode=search&q=pharmacy&source=mus"]];*/
        
        else
            if (np == nil){
                tryURL = 0;
                
                NearbyPharmacy *npObject = [[NearbyPharmacy alloc]initWithNibName:@"NearbyPharmacy" bundle:nil];
                self.np = npObject;
                [npObject release];
            
            
                np.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                [self presentModalViewController:np animated:YES];
                
                np = nil;
            }
        
        request = 1;
    }
    else{
        if(request == 0){
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Permission not Granted" message:@"Can not complete request." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        
            [alert show];
            [alert release];
            
            tryURL = 0;
            request = 1;
        }
    }
}

/*Go to Settings*/
- (IBAction)GoToPreferences:(id)sender{
    if (sets == nil){
        Preferences *setsObject = [[Preferences alloc]initWithNibName:@"Preferences" bundle:nil];
        self.sets = setsObject;
        [setsObject release];
    }
    
    sets.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:sets animated:YES];
    
    sets = nil;
}

/*Dragging the Emergency button*/
- (IBAction)EmergencyButton:(id)sender{
   // emergencypng.alpha = 1;
   // emergency.alpha = 0;
    emergencyArrows.hidden = false;
    [emergency addTarget:self action:@selector(EmergencyDrag:withEvent: ) forControlEvents: UIControlEventTouchDragOutside | UIControlEventTouchDragInside];
}

/*What happens during every step
 while dragging the emergency button*/
- (void) EmergencyDrag: (UIControl *) c withEvent: (UIEvent *) ev {
    c.center = [[[ev allTouches] anyObject] locationInView:nil];
    
    if(c.center.x >= 280 && c.center.y <= 50 ){
        if ([emergencyNumber.text isEqualToString:@""]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please setup Emergency Contact in Settings" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: @"Settings", nil];
            
            request = 2;
            
            [alert show];
            [alert release];
            c.center = CGPointMake(34, 378);
            emergencyArrows.hidden = true;
            
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.5];
            //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
            
            emergencyInstructions.alpha = 0;
            
            [UIView commitAnimations];
            
        }
        else{
            NSString *number = [[NSString alloc]initWithFormat:@"tel:%@",emergencyNumber.text];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]];
            c.center = CGPointMake(34, 378);
            emergencyArrows.hidden = true;
            
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.5];
            //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
            
            emergencyInstructions.alpha = 0;
            
            [UIView commitAnimations];
            
            [number release];
        }
    }
    
    //original coordinates : 34, 378
}

//if received a call while interacting with the emergency button; it would go back in place
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self EmergencyButtonLetGo:emergency];
}

//remove instructions after 2 seconds
- (void)removeEmergencyInstructions{
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
    
    emergencyInstructions.alpha = 0;
    
    [UIView commitAnimations];
    
}

/*Emergency will go back to first location when its released
 show instructions on screen for 2 seconds if the button is touched*/
- (IBAction)EmergencyButtonLetGo:(id)sender{    
    
    if (emergencyInstructions.alpha == 0) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        //[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
        
        emergencyInstructions.alpha = 1;
        
        [UIView commitAnimations];
    
        [self performSelector:@selector(removeEmergencyInstructions) withObject:nil afterDelay:3];
    }
        emergencyArrows.hidden = true;
        emergency.center = CGPointMake(34, 378);
}

/*Access the information tab of the program*/
- (IBAction)Information:(id)sender{
    if(about == nil){
        Information *aboutObject = [[Information alloc]initWithNibName:@"Information" bundle:nil];
        self.about = aboutObject;
        [aboutObject release];
    }
    
    about.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    [self presentModalViewController:about animated:YES];
}

//disable buttons while finding connection
//and enabled when connection is either found or not.
//emergency button is not disabled (can be used at any time)
- (void)enableButtons:(BOOL) yn{
    meds.enabled = yn;
    cal.enabled = yn;
    pharm.enabled = yn;
    history.enabled = yn;
    settings.enabled = yn;
    info.enabled = yn;
    nextReminder.enabled = yn;
}

/*Loads the next reminder via Load Next Notifications - displays the next reminder*/
- (IBAction)NextReminder:(id)sender{
    //default
    /*if([nextReminderLabel.text isEqualToString:@"No upcoming reminders"]){
        UIAlertView *reminder = [[UIAlertView alloc]initWithTitle:@"Next Reminder" message:@"No next reminders found" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [reminder show];
        [reminder release];
    }*/
    //
}

/*Displays the next upcoming notification*/
- (void)loadNextNotification{
    NSArray * notiflist = [[UIApplication sharedApplication] scheduledLocalNotifications];
    NSEnumerator *e = [notiflist objectEnumerator];
    UILocalNotification * notification;
    NSDate * today = [[NSDate alloc] init];
    
    while((notification = [e nextObject]) && ([notification.fireDate compare:today] < 0));
    
    if(notification == nil){
        nextReminderLabel.text = @"No upcoming reminders";
    }
    else{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
        
        if (daySettings == 0 && clockSettings == 0) {
            [dateFormatter setDateFormat:@"EEEE, h:mm a"];
        }else
            if (daySettings == 0 && clockSettings == 1) {
                [dateFormatter setDateFormat:@"EEEE, H:mm"];
            }else
                if (daySettings == 1 && clockSettings == 0) {
                    [dateFormatter setDateFormat:@"EEE, h:mm a"];
                }else{
                    [dateFormatter setDateFormat:@"EEE, H:mm"];
                }
        
        NSDate *date = notification.fireDate;
        NSTimeInterval time = [date timeIntervalSinceReferenceDate];
        date = [NSDate dateWithTimeIntervalSinceReferenceDate:time];
        NSString * dateString = [dateFormatter stringFromDate:date];
        
        NSString * medicineName = [notification.userInfo objectForKey:@"medName"];
        
        nextReminderLabel.text = [[NSString alloc]initWithFormat:@"%@ %@", medicineName, dateString];
    }
    
}

// Load emergency number and time format
- (void)loadSettings{
    
    aD = [[UIApplication sharedApplication] delegate];
    
    sqlite3_stmt * statement;
    NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
    const char * query_stmt = [enforceForeignKey UTF8String];
    

    
    NSString *loadSettings= @"SELECT emergency_contact, clock_setting, day_setting FROM Settings;";
    query_stmt = [loadSettings UTF8String];
    
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        if (sqlite3_step(statement) == SQLITE_ROW){

            NSString *emergencyNumberObject;
            const char * storedNumber = (char *)sqlite3_column_text(statement, 0);
            if(storedNumber != nil){
                emergencyNumberObject = [NSString stringWithUTF8String:storedNumber];
            }
            else
            {
                emergencyNumberObject = @"";
            }
            self.emergencyNumber.text = emergencyNumberObject;            
            int clockSettingObject = sqlite3_column_int(statement, 1);
            int daySettingObject = sqlite3_column_int(statement, 2);
            
            clockSettings = clockSettingObject;
            daySettings = daySettingObject;
        }
    }
    
    [loadSettings release];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    tryURL = 0;
    
    //Load Next Reminder
    [self loadSettings];
    [self loadNextNotification];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc{
    
    [pc release];
    [sets release];
    [about  release];
    [aD  release];
    [np  release];
    
    [meds release];
    [cal release];
    [pharm release];
    [settings release];
    [emergency release];
    [info release];
    [nextReminder release];
    [nextReminderLabel release];
    [emergencyNumber release];
    [emergencyArrows release];
    [webView release];
    [testingConnection release];
    [activityIndicator release];
    [URLActionImage release];
    
    [super dealloc];
}

@end